from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import ForumPost, User, UserType
from backend.schemas import ForumPostCreate, ForumPostResponse
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 路由前缀保持空
router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取所有帖子
@router.get("/api/forum-posts", response_model=List[ForumPostResponse])
async def list_forum_posts(db: Session = Depends(get_db)):
    """
    获取所有论坛帖子，按照发布时间降序
    """
    posts = db.query(ForumPost).order_by(ForumPost.post_time.desc()).all()
    return posts

# 发布新帖子
@router.post("/api/forum-posts", response_model=ForumPostResponse)
async def create_forum_post(post: ForumPostCreate, db: Session = Depends(get_db)):
    """
    发布新论坛帖子，需要提供用户ID
    """
    user = db.query(User).filter(User.user_id == post.user_id).first()
    if not user:
        logger.warning(f"用户不存在: user_id={post.user_id}")
        raise HTTPException(status_code=404, detail="用户不存在")
    db_post = ForumPost(
        user_id=post.user_id,
        title=post.title,
        content=post.content,
        parent_post_id=post.parent_post_id
    )
    db.add(db_post)
    db.commit()
    db.refresh(db_post)
    logger.info(f"成功发布帖子: post_id={db_post.post_id}")
    return db_post

# 删除帖子
@router.delete("/api/forum-posts/{post_id}")
async def delete_forum_post(post_id: int, user_id: int = Query(...), db: Session = Depends(get_db)):
    """
    删除指定帖子，只允许作者删除
    """
    post = db.query(ForumPost).filter(ForumPost.post_id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    # 验证权限 (作者或管理员才能删除)
    user = db.query(User).filter(User.user_id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    if post.user_id != user_id and user.user_type != UserType.admin:
        raise HTTPException(status_code=403, detail="无权限删除该帖子")
    db.delete(post)
    db.commit()
    return {"message": "帖子已删除"}

# 新增点赞接口
@router.post("/api/forum-posts/{post_id}/upvote", response_model=ForumPostResponse)
async def upvote_forum_post(post_id: int, db: Session = Depends(get_db)):
    """
    给帖子点赞，将 upvotes 加 1
    """
    post = db.query(ForumPost).filter(ForumPost.post_id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    post.upvotes += 1
    db.commit()
    db.refresh(post)
    return post

# 新增点踩接口
@router.post("/api/forum-posts/{post_id}/downvote", response_model=ForumPostResponse)
async def downvote_forum_post(post_id: int, db: Session = Depends(get_db)):
    """
    给帖子点踩，将 downvotes 加 1
    """
    post = db.query(ForumPost).filter(ForumPost.post_id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    post.downvotes += 1
    db.commit()
    db.refresh(post)
    return post
